package com.xs.ai.controller;

import com.xs.ai.services.KnowledgeBaseService;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.springframework.ai.document.Document;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author hhl
 * @version 1.0
 * @description
 * @date 2025/8/5 0:06
 */
@RestController
@RequestMapping("/api/knowledge")
public class KnowledgeBaseController {

    private final KnowledgeBaseService knowledgeBaseService;

    public KnowledgeBaseController(KnowledgeBaseService knowledgeBaseService) {
        this.knowledgeBaseService = knowledgeBaseService;
    }

    @PostMapping("/add")
    public ResponseEntity<String> addKnowledge(@RequestBody String content) {
        knowledgeBaseService.addDocumentToKnowledgeBase(content);
        return ResponseEntity.ok("知识已添加到知识库");
    }

    @GetMapping("/search")
    public ResponseEntity<List<String>> searchKnowledge(@RequestParam String query) {
        List<Document> results = knowledgeBaseService.searchRelevantDocuments(query);
        List<String> collect = results.stream().map(Document::getContent).collect(Collectors.toList());
        return ResponseEntity.ok(collect);
    }

    @PostMapping("/upload")
    public ResponseEntity<String> uploadPdf(@RequestParam("file") MultipartFile file) {
        try {
            byte[] bytes = file.getBytes();
            // 确保 uploads 目录存在
            Path uploadDir = Paths.get("uploads");
            if (!Files.exists(uploadDir)) {
                Files.createDirectories(uploadDir); // 创建 uploads 目录（包括父级，如果需要）
            }

            // 拼接目标文件路径
            Path path = uploadDir.resolve(file.getOriginalFilename());
            Files.write(path, bytes);

            // 使用PDFBox解析PDF
            PDDocument document = PDDocument.load(new File(path.toString()));
            PDFTextStripper stripper = new PDFTextStripper();
            String text = stripper.getText(document);
            document.close();

            return ResponseEntity.ok(text);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("解析失败");
        }
    }


}
